package chapter_04
import scala.collection.mutable.Map


object ChecksumAccumulator {
  private val cache = Map[String, Int]()
  
  def calculate(s: String): Int = 
    if (cache.contains(s))
      cache(s)
    else {
      // 注：因为关键字new只能用来实例化类，所以这里创造的新对象是ChecksumAccumulator
      // 类的一个实例，而不是同名的单例对象。
      val acc = new ChecksumAccumulator
      for (o <- s)
        acc.add(o.toByte)
        val cs = acc.checksum()
        cache += (s -> cs)
        cs
    }
}

class ChecksumAccumulator {
  // 4.1
  private var sum = 0
  
  def add(b: Byte): Unit = sum += b
  
  def checksum(): Int = ~(sum & 0xFF) + 1
}


object chapter_04 {
  
  def main(args: Array[String]) {
    val seasons = List("Summer", "of", "love")
    for (season <- seasons)
      println(season + ": " + ChecksumAccumulator.calculate(season))
  }
}